// import { Constant } from "../../../../../lib/app_constant";
// import Log from "../../../../../lib/common/Log";
// import { JL_RCSPOP } from "../../../../../lib/lib_rcsp";
// import { rcspDeviceOpSet } from "../../../../../lib/rcsp/RCSPDeviceManager";
// import { clone } from "../../../../../utils/util";
import { OPAlarm,StringUtil } from "../../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
import { RCSPOpAlarm } from "../../../../lib/rcsp-impl/rcsp";
import { authManager } from "../../../../api/auth-manager";
import api from "../../../../api/index";
const i18n = require('../../../../i18n/index');

// import { OPAlarm, StringUtil } from "../../../../lib/rcsp-protocol/rcsp-op-wrapper";
// pages/pageAlarm/pageAlarmDetail/index.ts
const TAG = "pageAlarmDetail"
const DEBUG = true
Page({

    /**
     * 页面的初始数据
     */
    data: { 
        l10n: {},
        title: "",
        mPickerArray: [
            ["00", "01", "02", "03", "04", "05", "06", "07",
                "08", "09", "10", "11", "12", "13", "14", "15",
                "16", "17", "18", "19", "20", "21", "22", "23"],
            ["00", "01", "02", "03", "04", "05", "06", "07",
                "08", "09", "10", "11", "12", "13", "14", "15",
                "16", "17", "18", "19", "20", "21", "22", "23",
                "24", "25", "26", "27", "28", "29", "30", "31",
                "32", "33", "34", "35", "36", "37", "38", "39",
                "40", "41", "42", "43", "44", "45", "46", "47",
                "48", "49", "50", "51", "52", "53", "54", "55",
                "56", "57", "58", "59"],
        ],
        mClockValue: [0, 0],
        mAlarmType: 0, //"0":新建闹钟 "1":编辑闹钟
        mAlarmName: i18n.t('alarm.defaultName'),
        mAlarmWeek: [0, 0, 0, 0, 0, 0, 0],
        mAlarmMode: 0,
        mAlarmSound: "",
        mHiddenmodalput: true, //修改设备名字提示框
        mTmpName: "",
        deviceId: null as number | null, // 设备ID
    },
    currentAlarmBean: OPAlarm.AlarmBean.prototype,

    ensureLang() {
        try {
            const saved = wx.getStorageSync('app:lang');
            const cur = i18n.getLang && i18n.getLang();
            if (saved && saved !== cur && i18n.setLang) i18n.setLang(saved);
        } catch(_) {}
    },
    updateTexts() {
        const t = (k: string, p?: any) => i18n.t('alarm.'+k,p);
        this.setData({ l10n: {
            finishBtn: t('finishBtn'),
            saveBtn: t('saveBtn'),
            deleteAlarmBtn: t('deleteAlarmBtn'),
            renameTitle: t('renameTitle'),
            ok: t('ok'),
            cancel: t('cancel')
        }});
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.ensureLang();
        this.updateTexts();
        let alarmType = Number.parseInt(options.alarmtype!!)
        // 动态设置导航栏标题
        wx.setNavigationBarTitle({
            title: alarmType == 0 ? i18n.t('alarm.detailNewTitle') : i18n.t('alarm.detailEditTitle')
        })

        // 获取设备ID（如果有的话）
        if (options.deviceId) {
            this.setData({
                deviceId: Number.parseInt(options.deviceId)
            });
        }

        // 初始化用户信息
        this.initUserInfo();

        const eventChannel = this.getOpenerEventChannel()
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        eventChannel.on('alarmBean', (data) => {
            // DEBUG && Log.d(TAG, "alarmBean", data)
            const temp = data.data as OPAlarm.AlarmBean
            let alarmBean = this.clone(temp)
            this.currentAlarmBean = alarmBean
            if (alarmBean.bellType == 0) {
                RCSPOpAlarm?.getAlarmDefaultBells().then((res) => {
                    this.setData({
                        mAlarmSound:
                            res[alarmBean.bellCluster].name
                    })
                })
            } else if (alarmBean.bellType == 1 && alarmBean.bellName) {
                this.setData({
                    mAlarmSound:
                        alarmBean.bellName
                })
            }
            this.setData({
                mClockValue: [alarmBean.hour!!, alarmBean.min!!],
                mAlarmType: alarmType,
                mAlarmName: alarmBean.name,
                mAlarmMode: alarmBean.repeatMode,
            })
        })

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.ensureLang();
        this.updateTexts();
        // 刷新用户信息
        this.refreshUserInfo();
    },

    /**
     * 刷新用户信息
     */
    async refreshUserInfo() {
        try {
            // 检查本地是否有用户信息
            const storedUserInfo = wx.getStorageSync('userInfo');
            const storedUserId = wx.getStorageSync('userId');
            
            if (!storedUserInfo || !storedUserId) {
                console.log('🔄 闹钟详情页面 - 本地用户信息缺失，重新获取');
                await this.initUserInfo();
            } else {
                console.log('✅ 闹钟详情页面 - 本地用户信息完整:', { userId: storedUserId, hasUserInfo: !!storedUserInfo });
            }
        } catch (error) {
            console.error('❌ 闹钟详情页面 - 刷新用户信息失败:', error);
        }
    },
    clone(obj: Object) {
        return JSON.parse(JSON.stringify(obj))
    },
    onPickerChange(e: any) {
        var array = this.data.mPickerArray
        var index_hour = e.detail.value[0]
        var index_min = e.detail.value[1]
        var hour = array[0][index_hour]
        var min = array[1][index_min]
        // DEBUG && Log.d(TAG, "onPickerChange", "时:" + hour + " 分:" + min)
        this.setData({
            mClockValue: [index_hour, index_min],
            mAlarmHour: hour,
            mAlarmMin: min,
        })
        this.currentAlarmBean.hour = Number.parseInt(hour)
        this.currentAlarmBean.min = Number.parseInt(min)
    },
    onTapWeek(e: any) {
        var index = e.currentTarget.dataset.index
        let alarmMode = this.data.mAlarmMode
        if (alarmMode == 1) {
            alarmMode = 254
        }
        if (((this.data.mAlarmMode >> (index + 1)) & 1) == 1) {//选中
            alarmMode -= (1 << (index + 1))
        } else {//没选中
            alarmMode += (1 << (index + 1))
        }
        if (alarmMode == 254) {
            alarmMode = 1
        }
        alarmMode = alarmMode % 254
        // DEBUG && Log.d(TAG, "onTapWeek", "index:" + index + " alarmMode:" + alarmMode)
        this.setData({
            mAlarmMode: alarmMode
        })
        this.currentAlarmBean.repeatMode = alarmMode
    },

    onTapName() {
        this.setData({
            mHiddenmodalput: !this.data.mHiddenmodalput,
            mTmpName: this.data.mAlarmName,
        })
    },

    //取消按钮
    onCancel: function () {
        this.setData({
            mHiddenmodalput: true,
            mTmpName: this.data.mAlarmName,
        });
    },
    //确认
    onConfirm: function () {
        this.setData({
            mHiddenmodalput: true,
        })
        const tmpName = this.data.mTmpName.trim()
        if (tmpName == "") {
            wx.showToast({
                title: i18n.t('alarm.nameEmpty'),
                icon: 'none',
                duration: 1000
            })
            this.setData({
                mTmpName: this.data.mAlarmName,
            });
            return
        }
        if (tmpName != this.data.mAlarmName) {
            const nameBytes = new Uint8Array(StringUtil.stringToData(0, this.data.mTmpName))
            if (nameBytes.length > 20) {
                wx.showToast({
                    title: i18n.t('alarm.nameTooLong'),
                    icon: 'none',
                    duration: 1000
                })
                this.setData({
                    mTmpName: this.data.mAlarmName,
                });
                return
            }
            // DEBUG && Log.d(TAG, "修改闹钟名字：" + this.data.mTmpName)
            this.currentAlarmBean.name = this.data.mTmpName
            this.setData({
                mAlarmName: this.data.mTmpName
            })
        }
    },
    onInput: function (e: any) {
        this.setData({
            mTmpName: e.detail.value
        })
    },
    onTapSound() {
        // const bellIndex = this.currentAlarmBean.bellCluster
        wx.navigateTo({
            url: '/pages/function_test/pageAlarmClock/pageAlarmDetail/pageAlarmBell/index',
            events: {
                bellArg: (data: any) => {
                    // if (data.type == 0) {//默认
                    //     this.currentAlarmBean.bellCluster = data.cluster
                    //     this.currentAlarmBean.devIndex = undefined
                    //     this.currentAlarmBean.bellType = 0
                    //     // rcspDeviceOpSet.OpAlarm?.getAlarmDefaultBells().then((res) => {
                    //     //     this.setData({
                    //     //         mAlarmSound:
                    //     //             res[data.cluster].name
                    //     // })

                    //     // })
                    // } else if (data.type == 1) {//文件
                    //     this.currentAlarmBean.bellCluster = data.cluster
                    //     this.currentAlarmBean.devIndex = data.devIndex
                    //     this.currentAlarmBean.bellType = 1
                    //     this.currentAlarmBean.bellName =data.bellName
                    //     this.setData({
                    //         mAlarmSound:
                    //     //             data.bellName
                    //     })
                    // }
                    this.currentAlarmBean.bellCluster = data.cluster
                    this.currentAlarmBean.devIndex = data.type == 0 ? undefined : data.devIndex
                    this.currentAlarmBean.bellType = data.type
                    this.currentAlarmBean.bellName = data.bellName
                    this.setData({
                        mAlarmSound:
                            data.bellName
                    })
                }
            }, success: (res) => {
                res.eventChannel.emit('alarmBean', { data: this.currentAlarmBean })
            }
        })
    },
    isSetting: false,
    onTapFinish() {
        if (this.isSetting) {
            return
        }
        this.isSetting = true
        RCSPOpAlarm?.addOrModifyAlarm([this.currentAlarmBean]).then((res: any) => {
            this.isSetting = false
            if (res) {
                wx.showToast({
                    title: i18n.t('alarm.addSuccess'),
                    icon: 'success',
                })
                wx.setNavigationBarTitle({
                    title: i18n.t('alarm.editAlarm')
                })
                this.setData({
                    mAlarmType: 1,
                })
                RCSPOpAlarm?.readAlarmList().then(() => {
                })
                
                // 同步闹钟到服务器
                this.syncAlarmToServer();
            } else {
                wx.showToast({
                    title: i18n.t('alarm.addFail'),
                    icon: 'error',
                })
            }
        }).catch((error: any) => {
            this.isSetting = false
            // DEBUG && Log.e(TAG, "addOrModifyAlarm error", error)
            wx.showToast({
                title: i18n.t('alarm.addFail'),
                icon: 'error',
            })
        })
    },
    onTapSave() {
        if (this.isSetting) {
            return
        }
        this.isSetting = true
        RCSPOpAlarm?.addOrModifyAlarm([this.currentAlarmBean]).then((res: any) => {
            this.isSetting = false
            if (res) {
                wx.showToast({
                    title: i18n.t('alarm.saveSuccess'),
                    icon: 'success',
                })
                RCSPOpAlarm?.readAlarmList()
                
                // 同步闹钟到服务器
                this.syncAlarmToServer();
            } else {
                wx.showToast({
                    title: i18n.t('alarm.saveFail'),
                    icon: 'error',
                })
            }
        }).catch((error: any) => {
            // DEBUG && Log.e(TAG, "addOrModifyAlarm error", error)
            this.isSetting = false
            wx.showToast({
                title: i18n.t('alarm.saveFail'),
                icon: 'error',
            })
        })
    },
    onTapDelete() {
        if (this.isSetting) {
            return
        }
        this.isSetting = true
        
        // 先删除设备闹钟
        RCSPOpAlarm?.deleteAlarm([this.currentAlarmBean]).then((res: any) => {
            if (res) {
                wx.showToast({
                    title: i18n.t('alarm.deleteSuccess'),
                    icon: 'success',
                })
                RCSPOpAlarm?.readAlarmList().then(() => {
                    wx.navigateBack()
                })
                
                // 从服务器删除闹钟（静默执行，不影响用户体验）
                this.deleteAlarmFromServer();
            } else {
                wx.showToast({
                    title: i18n.t('alarm.deleteFail'),
                    icon: 'error',
                })
            }
            this.isSetting = false
        }).catch((error: any) => {
            wx.showToast({
                title: i18n.t('alarm.deleteFail'),
                icon: 'error',
            })
            this.isSetting = false
        })
    },

    /**
     * 同步闹钟到服务器
     */
    async syncAlarmToServer() {
        try {
            // 从本地存储获取用户信息
            const storedUserInfo = wx.getStorageSync('userInfo');
            const storedUserId = wx.getStorageSync('userId');
            
            if (!storedUserInfo || !storedUserId) {
                console.log('本地用户信息缺失，跳过服务器同步');
                return;
            }
            
            const currentUser = { id: storedUserId, ...storedUserInfo };

            // 获取用户的设备ID
            let userDeviceId = this.data.deviceId || 1; // 默认设备ID为1
            
            try {
                // 尝试从服务器获取用户设备列表
                const devicesResponse = await api.getDevices();
                const deviceList = devicesResponse?.data?.data || devicesResponse?.data || [];
                
                if (Array.isArray(deviceList) && deviceList.length > 0) {
                    // 使用用户的第一个设备
                    const userDevice = deviceList[0];
                    userDeviceId = userDevice.id || userDevice.deviceId || 1;
                    console.log('获取到用户设备ID:', userDeviceId, '设备信息:', userDevice);
                } else {
                    console.warn('用户没有绑定设备，使用默认设备ID');
                }
            } catch (error) {
                console.warn('获取用户设备失败，使用默认设备ID:', error);
            }

            // 构建闹钟数据
            const alarmData = {
                userId: currentUser.id,
                deviceId: userDeviceId,
                name: this.currentAlarmBean.name || '闹钟',
                hour: this.currentAlarmBean.hour || 0,
                minute: this.currentAlarmBean.min || 0,
                repeatMode: this.currentAlarmBean.repeatMode || 0,
                isEnabled: this.currentAlarmBean.open || true,
                bellType: this.currentAlarmBean.bellType || 0,
                bellName: this.currentAlarmBean.bellName || '',
                status: 1
            };

            console.log('同步闹钟到服务器:', alarmData);

            // 调用API同步闹钟
            const response = await api.post('/api/alarm/sync', alarmData);
            
            if (response?.data?.code === 0) {
                console.log('闹钟同步到服务器成功');
                // 静默成功，不打扰用户
            } else {
                console.warn('闹钟同步到服务器失败:', response?.data?.message);
            }

        } catch (error: any) {
            console.error('同步闹钟到服务器异常:', error);
            // 静默失败，不影响主要功能
        }
    },

    /**
     * 从服务器删除闹钟
     */
    async deleteAlarmFromServer() {
        try {
            // 从本地存储获取用户信息
            const storedUserInfo = wx.getStorageSync('userInfo');
            const storedUserId = wx.getStorageSync('userId');
            
            if (!storedUserInfo || !storedUserId) {
                console.log('本地用户信息缺失，跳过服务器删除');
                return;
            }
            
            const currentUser = { id: storedUserId, ...storedUserInfo };

            // 获取用户的设备ID
            let userDeviceId = this.data.deviceId || 1; // 默认设备ID为1
            
            try {
                // 尝试从服务器获取用户设备列表
                const devicesResponse = await api.getDevices();
                const deviceList = devicesResponse?.data?.data || devicesResponse?.data || [];
                
                if (Array.isArray(deviceList) && deviceList.length > 0) {
                    // 使用用户的第一个设备
                    const userDevice = deviceList[0];
                    userDeviceId = userDevice.id || userDevice.deviceId || 1;
                    console.log('删除闹钟 - 获取到用户设备ID:', userDeviceId);
                } else {
                    console.warn('删除闹钟 - 用户没有绑定设备，使用默认设备ID');
                }
            } catch (error) {
                console.warn('删除闹钟 - 获取用户设备失败，使用默认设备ID:', error);
            }

            // 由于前端没有保存服务器闹钟ID，我们需要先查询匹配的闹钟
            const searchParams = {
                userId: currentUser.id,
                deviceId: userDeviceId,
                hour: this.currentAlarmBean.hour,
                minute: this.currentAlarmBean.min,
                name: this.currentAlarmBean.name
            };

            // 查询匹配的服务器闹钟
            const searchResponse = await api.get('/api/alarm/search', { params: searchParams });
            
            if (searchResponse?.data?.code === 0 && searchResponse.data.data?.length > 0) {
                // 找到匹配的闹钟，删除第一个
                const serverAlarmId = searchResponse.data.data[0].id;
                const deleteResponse = await api.delete(`/api/alarm/${serverAlarmId}`);
                
                if (deleteResponse?.data?.code === 0) {
                    console.log('服务器闹钟删除成功');
                } else {
                    console.warn('服务器闹钟删除失败');
                }
            } else {
                console.log('未找到匹配的服务器闹钟，无需删除');
            }

        } catch (error: any) {
            console.error('从服务器删除闹钟异常:', error);
            // 静默失败，不影响主要功能
        }
    },

    /**
     * 批量同步所有闹钟到服务器
     */
    async syncAllAlarmsToServer() {
        try {
            // 检查登录状态
            if (!authManager.isAuthenticated()) {
                console.log('用户未登录，跳过批量同步');
                return;
            }

            // 从本地存储获取用户信息
            const storedUserInfo = wx.getStorageSync('userInfo');
            const storedUserId = wx.getStorageSync('userId');
            
            if (!storedUserInfo || !storedUserId) {
                console.log('本地用户信息缺失，跳过批量同步');
                return;
            }
            
            const currentUser = { id: storedUserId, ...storedUserInfo };

            // 获取当前设备的所有闹钟
            const alarmListResponse = await RCSPOpAlarm?.readAlarmList();
            if (!alarmListResponse?.alarmBeanList) {
                console.log('无法获取设备闹钟列表');
                return;
            }

            const alarms = alarmListResponse.alarmBeanList;
            if (alarms.length === 0) {
                console.log('设备无闹钟，无需同步');
                return;
            }

            // 构建批量同步数据
            const batchAlarms = alarms.map(alarm => ({
                userId: currentUser.id,
                deviceId: this.data.deviceId || 1,
                name: alarm.name || '闹钟',
                hour: alarm.hour || 0,
                minute: alarm.min || 0,
                repeatMode: alarm.repeatMode || 0,
                isEnabled: alarm.open || true,
                bellType: alarm.bellType || 0,
                bellName: alarm.bellName || '',
                status: 1
            }));

            console.log('批量同步闹钟到服务器:', batchAlarms);

            // 调用批量同步API
            const response = await api.post('/api/alarm/sync/batch', batchAlarms);
            
            if (response?.data?.code === 0) {
                console.log('批量同步闹钟到服务器成功');
            } else {
                console.warn('批量同步闹钟到服务器失败:', response?.data?.message);
            }

        } catch (error: any) {
            console.error('批量同步闹钟到服务器异常:', error);
        }
    },

    /**
     * 初始化用户信息
     */
    async initUserInfo() {
        try {
            // 尝试从API获取用户信息
            const response = await api.getUserInfo();
            
            // 添加详细的响应日志
            console.log('🔍 闹钟详情页面 - API响应详情:', {
                statusCode: response?.statusCode,
                responseData: response?.data,
                code: response?.data?.code,
                message: response?.data?.message,
                hasData: !!response?.data?.data,
                dataType: typeof response?.data?.data,
                dataKeys: response?.data?.data ? Object.keys(response?.data?.data) : []
            });
            
            // 检查响应结构 - 修复：处理code可能是字符串的情况
            const responseCode = response?.data?.code;
            const isSuccess = responseCode === 0 || responseCode === "0" || responseCode === 200 || responseCode === "200";
            
            if (isSuccess && response.data.data) {
                const userInfo = response.data.data;
                console.log('✅ 闹钟详情页面 - 成功获取用户信息:', userInfo);
                
                // 保存到本地存储
                wx.setStorageSync('userInfo', userInfo);
                if (userInfo.id) {
                    wx.setStorageSync('userId', userInfo.id);
                }
            } else if (isSuccess && !response.data.data) {
                // 如果code是成功但没有data，可能是空数据的情况
                console.warn('⚠️ 闹钟详情页面 - API返回成功但无用户数据，可能用户未登录或数据为空');
                
                // 尝试从响应中查找用户信息
                const possibleUserInfo = response.data.user || response.data.userInfo || response.data;
                if (possibleUserInfo && (possibleUserInfo.id || possibleUserInfo.userId)) {
                    console.log('🔍 闹钟详情页面 - 从响应中提取到可能的用户信息:', possibleUserInfo);
                    const userInfo = {
                        id: possibleUserInfo.id || possibleUserInfo.userId,
                        nickname: possibleUserInfo.nickname || possibleUserInfo.username || '智能水杯用户',
                        username: possibleUserInfo.username || possibleUserInfo.nickname
                    };
                    
                    wx.setStorageSync('userInfo', userInfo);
                    wx.setStorageSync('userId', userInfo.id);
                    console.log('✅ 闹钟详情页面 - 已保存提取的用户信息');
                }
            } else {
                console.warn('⚠️ 闹钟详情页面 - 获取用户信息失败:', {
                    code: response?.data?.code,
                    message: response?.data?.message,
                    fullResponse: response?.data
                });
            }
        } catch (error) {
            console.error('❌ 闹钟详情页面 - 初始化用户信息异常:', error);
        }
    }
})